package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Override
    public JSONObject uploadTrack(MultipartFile file) {
        if(file.isEmpty()){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        VodUploadClient client =
                new VodUploadClient(vodConstantProperties.getSecretId(),
                        vodConstantProperties.getSecretKey());
        //2、封装请求参数
        VodUploadRequest request = new VodUploadRequest();
        //2.1 要上传文件的路径
        // 腾讯云vod必须通过文件路径上传： 所以我们需要先将要上传的文件保存到本地 然后再加载上传
        String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
        request.setMediaFilePath(tempPath);
        //2.2 要上传文件的封面
        request.setCoverFilePath("F:\\a.jpg");
        //2.3 上传文件后vod的任务流(工作流：审核、转码...)
        request.setProcedure(vodConstantProperties.getProcedure());//可以省略
        //2.4 上传文件保存到vod中的哪个应用中: 如果是默认应用 可以省略
        request.setSubAppId(vodConstantProperties.getAppId());//到 云点播->应用列表 默认应用
        try {
            //3、上传文件 到vod 并接收返回的结果
            VodUploadResponse response = client.upload("ap-shanghai", request);
            //打印响应数据
//            log.info(" 时间:{} , Upload Response = {}",new Date(), JSON.toJSONString(response));
            JSONObject jsonObject = new JSONObject();
            String fileId = response.getFileId();
            String mediaUrl = response.getMediaUrl();
            jsonObject.put("mediaFileId",fileId);
            jsonObject.put("mediaUrl",mediaUrl);
            return jsonObject;
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
            throw new GuiguException(ResultCodeEnum.VOD_UPLOAD_ERROR);
        }
    }
    //根据文件id获取媒体信息
    @SneakyThrows
    @Override
    public TrackMediaInfoVo getTrackMediaInfoVo(String mediaFileId) {
        Credential cred = new Credential(vodConstantProperties.getSecretId(),
                vodConstantProperties.getSecretKey());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("vod.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        VodClient client = new VodClient(cred, "", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
        String[] fileIds1 = {mediaFileId};
        req.setFileIds(fileIds1);

        // 返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
        DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
        // 输出json格式的字符串回包
        MediaInfo mediaInfo = resp.getMediaInfoSet()[0];
        MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
        MediaMetaData metaData = mediaInfo.getMetaData();

        TrackMediaInfoVo vo = new TrackMediaInfoVo();
        vo.setDuration(metaData.getDuration());
        vo.setType(basicInfo.getType());
        vo.setSize(metaData.getSize());
        vo.setMediaUrl(basicInfo.getMediaUrl());
        return vo;
    }

    @Override
    public void deleteVodMedia(String mediaFileId) {
        try {
            Credential cred = new Credential(vodConstantProperties.getSecretId(),
                    vodConstantProperties.getSecretKey());
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("vod.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            // 返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            DeleteMediaResponse resp = client.DeleteMedia(req);
            //判断 如果删除失败 可以抛出异常
        } catch (TencentCloudSDKException e) {
            throw new GuiguException(ResultCodeEnum.VOD_DELETE_ERROR);
        }
    }
}
